﻿/*
*      
*          ┌─┐       ┌─┐
*       ┌──┘ ┴───────┘ ┴──┐
*       │                 │
*       │       ───       │
*       │  ─┬┘       └┬─  │
*       │                 │
*       │       ─┴─       │
*       │                 │
*       └───┐         ┌───┘
*           │         │
*           │         │
*           │         │
*           │         └──────────────┐
*           │                        │
*           │                        ├─┐
*           │                        ┌─┘    
*           │                        │
*           └─┐  ┐  ┌───────┬──┐  ┌──┘         
*             │ ─┤ ─┤       │ ─┤ ─┤         
*             └──┴──┘       └──┴──┘ 
*                 神兽保佑 
*                 代码无BUG! 
*  Author shang
*  2022-07-21 12:22:25
*/

using System.Text.Json;
using Autofac.Annotation;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using TS.Common;
using TS.Model;
using TS.Services;

namespace TaskScheduling.Middleware;

[Component]
public class ApiAuthorizeAttribute : Attribute, IAuthorizationFilter
{
    private readonly AuthorizationHandlerSerivce _authorizationHandlerSerivce;

    public ApiAuthorizeAttribute( AuthorizationHandlerSerivce authorizationHandlerSerivce)
    {
        _authorizationHandlerSerivce = authorizationHandlerSerivce;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (HasAllowAnonymous(context) == false)
        {
            var token = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            (bool, string) validate = (false, "Token无效");
            validate = _authorizationHandlerSerivce.ValidateJWTAuthentication(token);

            if (validate.Item1)
            {
                context.HttpContext.Items["user"] =
                    JsonSerializer.Deserialize<AuthenUser>((token.Split(".")[1]).Base64Decode());
            }
            else
            {
                context.HttpContext.Items["user"] = null;
            }

            if (context.HttpContext.Items["user"] == null)
            {
                // not logged in
                context.Result = new JsonResult(new {code = 401, msg = new string[] {"登录过期"}})
                    {StatusCode = StatusCodes.Status401Unauthorized}; //这个可控 看前端处理
            }
        }
    }


    /// <summary>
    /// 过滤不需要
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private static bool HasAllowAnonymous(AuthorizationFilterContext context)
    {
        var result = false;

        var url = context.HttpContext.Request.Path.ToString();
        if (url == "/Home/Login" || url == "/Health/Index")
        {
            return true;
        }

        return result;
    }
}